﻿using CBS.DB;
using CBS.DB.CBSEntity;
using CBS.Model.Enum;
using CBS.Model.ManageModel;
using CBS.Model.ViewModel;
using MySqlConnector;
using System.Data;

namespace CBS.APP
{
    public class StudentSignInApp
    {
        //public static bool CreateStudentSignIn(StudentSignInViewModel signIn)
        //{
        //    using CBSContext cbs = new();
        //    cbs_student_sign_detail detail = new()
        //    {
        //        LessonId = signIn.LessonId,
        //        StudentId = signIn.StudentId,

        //    };


        //    cbs.cbs_student_sign_detail.Add(detail);
        //    return cbs.SaveChanges() > 0;
        //}

        public static List<StudentSignInInfoViewModel> GetList(Pagination pager, int Semester, int GradeId, int ClassId, int CourseId, int LessonId, string StudentInfo)
        {
            string sql = @"select c.SighInId,a.SemesterId,d.SemesterName,a.CoursePlanId,a.CoursePlanName,i.StudentId,i.StudentName,h.TeacherId,h.TeacherName,b.StartTime,b.EndTime,c.IsSupplement,c.IsTaster,e.GradeName,f.ClassName,g.CourseName
from cbs_course_plan a 
	inner join cbs_lesson b on a.CoursePlanId = b.CoursePlanId
	inner join cbs_student_sign_detail c on b.LessonId = c.LessonId
	left join cbs_semester d on a.SemesterId = d.SemesterId
	left join cbs_grade e on a.GradeId = e.GradeId
	left join cbs_class f on a.ClassId = f.ClassId
	left join cbs_course g on a.CourseId = g.CourseId
	left join cbs_teacher h on b.TeacherId = h.TeacherId
	left join cbs_student i on c.StudentId = i.StudentId
where a.SemesterId = @semesterId
and (@gradeId = 0 or a.GradeId = @gradeId)
and (@classId = 0 or a.ClassId = @classId)
and (@courseId = 0 or a.CourseId = @courseId)
and (@lessonId = 0 or b.LessonId = @lessonId)
and (@studentInfo = '' or i.StudentName like @studentInfo)";
            MySqlParameter[] para =
            {
                new MySqlParameter("@semesterId", Semester),
                new MySqlParameter("@gradeId", GradeId),
                new MySqlParameter("@classId", ClassId),
                new MySqlParameter("@courseId", CourseId),
                new MySqlParameter("@lessonId", LessonId),
                new MySqlParameter("@studentInfo", $"%{StudentInfo}%"),
            };

            return DBHelper.FindListOrderBy<StudentSignInInfoViewModel>(sql, pager, FromPositionInSql.First, para);
        }

        public static bool DeleteStudentSignIn(int signInId)
        {
            using CBSContext cbs = new();
            using var transaction = cbs.Database.BeginTransaction();
            try
            {
                var signIn = cbs.cbs_student_sign_detail.FirstOrDefault(t => t.SighInId == signInId);
                if (signIn == null) { transaction.Rollback(); return false; }

                var lesson = cbs.cbs_lesson.FirstOrDefault(t => t.LessonId == signIn.LessonId);
                if (lesson == null) { transaction.Rollback(); return false; }

                var coursePlan = cbs.cbs_course_plan.FirstOrDefault(t => t.CoursePlanId == lesson.CoursePlanId);
                if (coursePlan == null) { transaction.Rollback(); return false; }

                //取消签到消费记录
                var costData = cbs.cbs_student_cost.Where(t => t.StudentId == signIn.StudentId && t.CostCoursePlanId == coursePlan.CoursePlanId && t.CostLessonId == lesson.LessonId).ToList();
                cbs.cbs_student_cost.RemoveRange(costData);
                cbs.SaveChanges();

                if (!signIn.IsTaster)
                {
                    var stuAmount = cbs.cbs_student_amount.FirstOrDefault(t => t.StudentId == signIn.StudentId);
                    if (stuAmount == null) { transaction.Rollback(); return false; }

                    stuAmount.Balance += coursePlan.CoursePrice;
                    cbs.SaveChanges();

                    var stuSemesterAmount = cbs.cbs_student_semester_amount.FirstOrDefault(t => t.StudentId == signIn.StudentId && t.SemesterId == coursePlan.SemesterId);
                    if (stuSemesterAmount == null) { transaction.Rollback(); return false; }
                    stuSemesterAmount.Payable -= coursePlan.CoursePrice;
                    cbs.SaveChanges();

                    var teaSemesterAmount = cbs.cbs_teacher_semester_amount.FirstOrDefault(t => t.TeacherId == lesson.TeacherId && t.SemesterId == coursePlan.SemesterId);
                    if (teaSemesterAmount == null) { transaction.Rollback(); return false; }
                    teaSemesterAmount.Receivable -= coursePlan.CoursePrice;
                    cbs.SaveChanges();
                }


                if (signIn.IsSupplement)
                {
                    var supplement = cbs.cbs_student_supplement_lesson.FirstOrDefault(t => t.SignInId == signIn.SighInId);
                    if (supplement != null)
                    {
                        cbs.cbs_student_supplement_lesson.Remove(supplement);
                        cbs.SaveChanges();
                    }
                }

                cbs.cbs_student_sign_detail.Remove(signIn);
                cbs.SaveChanges();

                transaction.Commit();
                return true;
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
        }

        public static bool BatchDeleteStudentSignIn(int semesterId, int gradeId, int classId, int courseId, int lessonId, string studentInfo)
        {
            using CBSContext cbs = new();
            using var transaction = cbs.Database.BeginTransaction();
            try
            {
                var coursePlan = cbs.cbs_course_plan.Where(t => t.SemesterId == semesterId && (gradeId == 0 || t.GradeId == gradeId) && (classId == 0 || t.ClassId == classId) && (courseId == 0 || t.CourseId == courseId)).ToList();
                if (coursePlan == null) { transaction.Rollback(); return false; }

                var signinInfo = (from courP in cbs.cbs_course_plan
                                  join lesson in cbs.cbs_lesson on courP.CoursePlanId equals lesson.CoursePlanId
                                  join signin in cbs.cbs_student_sign_detail on lesson.LessonId equals signin.LessonId
                                  join stu in cbs.cbs_student on signin.StudentId equals stu.StudentId
                                  where courP.SemesterId == semesterId
                                  && (gradeId == 0 || courP.GradeId == gradeId)
                                  && (classId == 0 || courP.ClassId == classId)
                                  && (courseId == 0 || courP.CourseId == courseId)
                                  && (lessonId == 0 || signin.LessonId == lessonId)
                                  && (studentInfo == "" || stu.StudentName.Contains(studentInfo))
                                  select new { signin, lesson.TeacherId, courP.CoursePlanId, courP.CoursePrice }).ToList();
                var signinedData = signinInfo.Select(t => new { t.signin.StudentId, t.TeacherId, t.CoursePlanId, t.CoursePrice }).ToList();

                if (signinedData == null) { transaction.Rollback(); return false; }
                int[] stus = signinedData.Select(t => t.StudentId).ToArray();
                int[] tasterStus = signinInfo.Where(t => t.signin.IsTaster == true).Select(t => t.signin.StudentId).ToArray();


                var stuAmounts = cbs.cbs_student_amount.Where(t => stus.Contains(t.StudentId)).ToList();
                cbs.AttachRange(stuAmounts);
                //学期账户结算
                var stusSemesterAmount = cbs.cbs_student_semester_amount.Where(t => stus.Contains(t.StudentId) && t.SemesterId == semesterId).ToList();
                cbs.AttachRange(stusSemesterAmount);
                //decimal price = coursePlan.CoursePrice.Value;

                //取消签到消费记录
                var costData = (from courP in cbs.cbs_course_plan
                                join lesson in cbs.cbs_lesson on courP.CoursePlanId equals lesson.CoursePlanId
                                join signin in cbs.cbs_student_sign_detail on lesson.LessonId equals signin.LessonId
                                join stu in cbs.cbs_student on signin.StudentId equals stu.StudentId
                                join cost in cbs.cbs_student_cost on new { A = signin.StudentId, B = lesson.LessonId } equals new { A = cost.StudentId, B = cost.CostLessonId }
                                where courP.SemesterId == semesterId
                                    && (gradeId == 0 || courP.GradeId == gradeId)
                                    && (classId == 0 || courP.ClassId == classId)
                                    && (courseId == 0 || courP.CourseId == courseId)
                                    && (lessonId == 0 || signin.LessonId == lessonId)
                                    && (studentInfo == "" || stu.StudentName.Contains(studentInfo))
                                select cost).ToList();
                cbs.cbs_student_cost.RemoveRange(costData);
                cbs.SaveChanges();


                //结算学生账户余额
                for (int i = 0; i < stuAmounts.Count; i++)
                {
                    stuAmounts[i].Balance = stuAmounts[i].Balance + signinInfo.Where(t => t.signin.StudentId == stuAmounts[i].StudentId && t.signin.IsTaster == false).Sum(t => t.CoursePrice);
                    cbs.Entry(stuAmounts[i]).Property(x => x.Balance).IsModified = true;

                    var stuSemesterAmount = stusSemesterAmount.FirstOrDefault(t => t.StudentId == stuAmounts[i].StudentId);
                    if (stuSemesterAmount != null)
                    {
                        stuSemesterAmount.Payable -= signinInfo.Where(t => t.signin.StudentId == stuAmounts[i].StudentId && t.signin.IsTaster == false).Sum(t => t.CoursePrice);
                    }
                    else
                    {
                        stuSemesterAmount = new cbs_student_semester_amount
                        {
                            StudentId = stuAmounts[i].StudentId,
                            SemesterId = semesterId,
                            Payable = 0,
                            Payment = 0
                        };
                        cbs.cbs_student_semester_amount.Add(stuSemesterAmount);
                    }
                }
                cbs.SaveChanges();

                var teaIds = signinedData.Select(t => t.TeacherId).ToArray().Distinct();
                var teacherSemesterAmount = cbs.cbs_teacher_semester_amount.Where(t => teaIds.Contains(t.TeacherId) && t.SemesterId == semesterId);
                if (teacherSemesterAmount == null)
                {
                    foreach (var item in teaIds)
                    {
                        cbs.cbs_teacher_semester_amount.Add(new cbs_teacher_semester_amount
                        {
                            TeacherId = item,
                            SemesterId = semesterId,
                            Receivable = 0,
                            Reeipts = 0
                        });

                    }

                    cbs.SaveChanges();
                }
                else
                {

                    foreach (var item in teacherSemesterAmount)
                    {
                        item.Receivable -= signinInfo.Where(t => t.TeacherId == item.TeacherId && t.signin.IsTaster == false).Sum(t => t.CoursePrice);
                    }
                    cbs.SaveChanges();
                }

                var signInData = signinInfo.Select(t => t.signin).ToList();
                if (signInData.Any(t => t.IsSupplement == true))
                {
                    var signinIds = signInData.Where(t => t.IsSupplement == true).Select(t => t.SighInId).ToArray();
                    List<cbs_student_supplement_lesson> supplement = cbs.cbs_student_supplement_lesson.Where(t => signinIds.Contains(t.SignInId)).ToList();

                    if (supplement.Count > 0)
                    {
                        cbs.cbs_student_supplement_lesson.RemoveRange(supplement);
                        cbs.SaveChanges();
                    }
                }

                if (signinedData.Count > 0)
                {
                    cbs.cbs_student_sign_detail.RemoveRange(signInData);

                    cbs.SaveChanges();
                }

                transaction.Commit();
                return true;
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
        }

        public static bool ExistsSignInData(int semesterId, int lessonId)
        {
            using CBSContext cbs = new();
            var signinedData = cbs.cbs_student_sign_detail.Where(t => t.LessonId == lessonId).ToList();

            return signinedData.Count > 0;
        }

        public static bool AllSignUpArrive(int semesterId, int lessonId, out string msg)
        {
            msg = "";

            using CBSContext cbs = new();
            using var transaction = cbs.Database.BeginTransaction();
            try
            {
                var lesson = cbs.cbs_lesson.FirstOrDefault(t => t.LessonId == lessonId);
                int coursePlanId = lesson.CoursePlanId;
                var coursePlan = cbs.cbs_course_plan.FirstOrDefault(t => t.CoursePlanId == coursePlanId);
                if (coursePlan == null)
                {
                    transaction.Rollback();
                    return false;
                }

                //清空已签到数据
                var signinedData = cbs.cbs_student_sign_detail.Where(t => t.LessonId == lessonId).ToList();
                var stus = signinedData.Select(t => t.StudentId).ToList();

                var stuAmounts = cbs.cbs_student_amount.Where(t => stus.Contains(t.StudentId)).ToList();
                cbs.AttachRange(stuAmounts);
                //学期账户结算
                var stusSemesterAmount = cbs.cbs_student_semester_amount.Where(t => stus.Contains(t.StudentId) && t.SemesterId == coursePlan.SemesterId).ToList();
                cbs.AttachRange(stusSemesterAmount);
                decimal price = coursePlan.CoursePrice * lesson.LessonTimeLong;

                //取消签到消费记录
                var costData = cbs.cbs_student_cost.Where(t => stus.Contains(t.StudentId) && t.CostCoursePlanId == coursePlan.CoursePlanId && t.CostLessonId == lessonId).ToList();

                cbs.cbs_student_cost.RemoveRange(costData);
                cbs.SaveChanges();

                //结算学生账户余额
                for (int i = 0; i < stuAmounts.Count; i++)
                {
                    decimal beforeSemesterBalance = stuAmounts[i].Balance;
                    stuAmounts[i].Balance = stuAmounts[i].Balance + price;
                    cbs.Entry(stuAmounts[i]).Property(x => x.Balance).IsModified = true;

                    var stuSemesterAmount = stusSemesterAmount.FirstOrDefault(t => t.StudentId == stuAmounts[i].StudentId);
                    if (stuSemesterAmount != null)
                    {
                        stuSemesterAmount.Payable -= price;
                    }
                    else
                    {
                        stuSemesterAmount = new cbs_student_semester_amount
                        {
                            StudentId = stuAmounts[i].StudentId,
                            SemesterId = coursePlan.SemesterId,
                            Payable = 0,
                            Payment = 0,
                            BeforeSemesterBalance = beforeSemesterBalance,
                        };
                        cbs.cbs_student_semester_amount.Add(stuSemesterAmount);
                    }
                }
                cbs.SaveChanges();

                //结算教师账户信息
                var teacherSemesterAmount = cbs.cbs_teacher_semester_amount.FirstOrDefault(t => t.TeacherId == lesson.TeacherId && t.SemesterId == coursePlan.SemesterId);
                if (teacherSemesterAmount == null)
                {
                    teacherSemesterAmount = new cbs_teacher_semester_amount
                    {
                        TeacherId = lesson.TeacherId,
                        SemesterId = coursePlan.SemesterId,
                        Receivable = 0,
                        Reeipts = 0
                    };

                    cbs.cbs_teacher_semester_amount.Add(teacherSemesterAmount);
                    cbs.SaveChanges();
                }
                else
                {
                    teacherSemesterAmount.Receivable -= price * stus.Count;
                    cbs.SaveChanges();
                }

                //删除已有签到信息
                if (signinedData.Count > 0)
                {
                    cbs.cbs_student_sign_detail.RemoveRange(signinedData);

                    cbs.SaveChanges();
                }

                var signUpData = (from signup in cbs.cbs_student_signup
                                  join stu in cbs.cbs_student on signup.StudentId equals stu.StudentId
                                  where signup.CoursePlanId == coursePlanId
                                  select stu).ToList();

                var data = signUpData.Select(t => new cbs_student_sign_detail() { StudentId = t.StudentId, LessonId = lessonId, IsSupplement = false, IsTaster = false }).ToList();

                //重新添加签到信息
                cbs.cbs_student_sign_detail.AddRange(data);
                cbs.SaveChanges();

                SignInOperation(cbs, data, coursePlan, lesson, semesterId);

                transaction.Commit();
                return true;
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return false;
            }
        }

        private static void SignInOperation(CBSContext cbs, List<cbs_student_sign_detail> data, cbs_course_plan coursePlan, cbs_lesson lesson, int semesterId)
        {
            try
            {

                int[] stus = data.Select(t => t.StudentId).ToArray();
                int[] tasterStus = data.Where(t => t.IsTaster == true).Select(t => t.StudentId).ToArray();

                var stuAmounts = cbs.cbs_student_amount.Where(t => stus.Contains(t.StudentId)).ToList();

                cbs.AttachRange(stuAmounts);
                //学期账户结算
                var stusSemesterAmount = cbs.cbs_student_semester_amount.Where(t => stus.Contains(t.StudentId) && t.SemesterId == coursePlan.SemesterId).ToList();
                cbs.AttachRange(stusSemesterAmount);
                decimal price = coursePlan.CoursePrice * lesson.LessonTimeLong;

                //添加消费记录
                var costData = data.Select(t => new cbs_student_cost { StudentId = t.StudentId, CostSemesterId = coursePlan.SemesterId, CostCoursePlanId = coursePlan.CoursePlanId, CostLessonId = lesson.LessonId, Cost = price, CostTime = lesson.StartTime, CostType = (int)StudentCostEnum.TakeClass }).ToList();
                foreach (var item in costData)
                {
                    item.BeforeAmount = stuAmounts.FirstOrDefault(t => t.StudentId == item.StudentId).Balance;
                }
                cbs.cbs_student_cost.AddRange(costData);
                cbs.SaveChanges();

                //结算学生账户余额
                for (int i = 0; i < stuAmounts.Count; i++)
                {
                    decimal beforeSemesterBalance = stuAmounts[i].Balance;
                    if (!tasterStus.Contains(stuAmounts[i].StudentId))
                    {
                        stuAmounts[i].Balance = stuAmounts[i].Balance - price;
                        cbs.Entry(stuAmounts[i]).Property(x => x.Balance).IsModified = true;
                    }

                    var stuSemesterAmount = stusSemesterAmount.FirstOrDefault(t => t.StudentId == stuAmounts[i].StudentId);
                    if (stuSemesterAmount != null)
                    {
                        if (!tasterStus.Contains(stuAmounts[i].StudentId))
                        {
                            stuSemesterAmount.Payable += price;
                        }
                    }
                    else
                    {
                        if (!tasterStus.Contains(stuAmounts[i].StudentId))
                        {
                            stuSemesterAmount = new cbs_student_semester_amount
                            {
                                StudentId = stuAmounts[i].StudentId,
                                SemesterId = coursePlan.SemesterId,
                                Payable = price,
                                Payment = 0,
                                BeforeSemesterBalance = beforeSemesterBalance,
                            };
                        }
                        else
                        {
                            stuSemesterAmount = new cbs_student_semester_amount
                            {
                                StudentId = stuAmounts[i].StudentId,
                                SemesterId = coursePlan.SemesterId,
                                Payable = 0,
                                Payment = 0,
                                BeforeSemesterBalance = beforeSemesterBalance,
                            };
                        }

                        cbs.cbs_student_semester_amount.Add(stuSemesterAmount);
                    }
                }
                cbs.SaveChanges();


                var teacherSemesterAmount = cbs.cbs_teacher_semester_amount.FirstOrDefault(t => t.TeacherId == lesson.TeacherId && t.SemesterId == coursePlan.SemesterId);
                if (teacherSemesterAmount == null)
                {
                    teacherSemesterAmount = new cbs_teacher_semester_amount
                    {
                        TeacherId = lesson.TeacherId,
                        SemesterId = coursePlan.SemesterId,
                        Receivable = price * (stus.Length - tasterStus.Length),
                        Reeipts = 0
                    };

                    cbs.cbs_teacher_semester_amount.Add(teacherSemesterAmount);
                    cbs.SaveChanges();
                }
                else
                {
                    teacherSemesterAmount.Receivable += price * (stus.Length - tasterStus.Length);
                    cbs.SaveChanges();
                }


                //结算分红
                var bonus = cbs.cbs_student_bonus.Where(t => t.SemesterId == semesterId && stus.Contains(t.StudentId) && t.IsSatisfyingCondition == false).ToList();
                int[] bonusStu = bonus.Select(t => t.StudentId).ToArray();

                var bonusCount = from cp in cbs.cbs_course_plan
                                 join less in cbs.cbs_lesson on cp.CoursePlanId equals lesson.CoursePlanId
                                 join signin in cbs.cbs_student_sign_detail on lesson.LessonId equals signin.LessonId
                                 where cp.SemesterId == semesterId
                                 group new { cp.SemesterId, cp.CoursePrice, cp.ClassTimeLong, signin.StudentId } by new { cp.SemesterId, cp.CoursePrice, cp.ClassTimeLong, signin.StudentId } into g
                                 select new
                                 {
                                     SemesterId = g.Key.SemesterId,
                                     StudentId = g.Key.StudentId,
                                     LessonCost = g.Key.CoursePrice * g.Sum(x => x.ClassTimeLong),
                                 };

                for (int i = 0; i < bonus.Count; i++)
                {
                    var countContadion = bonusCount.First(t => t.StudentId == bonus[i].StudentId);
                    if (countContadion.LessonCost >= 1000)
                    {
                        cbs.Attach(bonus[i]);

                        //
                        bonus[i].IsSatisfyingCondition = true;
                        cbs.Entry(bonus[i]).Property(x => x.IsSatisfyingCondition).IsModified = true;
                    }
                }
                cbs.SaveChanges();
            }
            catch
            {
                throw;
            }

        }

        public static bool ImportNoStudentSignIn(string noSignInStudent, int semesterId, int lessonId, out string msg)
        {
            msg = "";
            string[] students = noSignInStudent.Replace('，', ',').Split(',', StringSplitOptions.RemoveEmptyEntries);
            using CBSContext cbs = new();
            using var transaction = cbs.Database.BeginTransaction();
            try
            {
                var lesson = cbs.cbs_lesson.FirstOrDefault(t => t.LessonId == lessonId);
                int coursePlanId = lesson.CoursePlanId;
                var coursePlan = cbs.cbs_course_plan.FirstOrDefault(t => t.CoursePlanId == coursePlanId);

                var signUpData = (from signup in cbs.cbs_student_signup
                                  join stu in cbs.cbs_student on signup.StudentId equals stu.StudentId
                                  where signup.CoursePlanId == coursePlanId
                                  select stu).ToList();

                foreach (var item in students)
                {
                    signUpData.RemoveAll(t => t.StudentName == item);
                }

                if (signUpData.Count == 0)
                {
                    msg = "未查询到有效数据。";
                    return false;
                }

                var data = signUpData.Select(t => new cbs_student_sign_detail() { StudentId = t.StudentId, LessonId = lessonId, IsSupplement = false, IsTaster = false }).ToList();

                cbs.cbs_student_sign_detail.AddRange(data);
                cbs.SaveChanges();

                SignInOperation(cbs, data, coursePlan, lesson, semesterId);

                transaction.Commit();
                return true;
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return false;
            }
        }

        public static bool ImportSupplementStudent(string supplementStudent, DateTime? supplementStartTime, DateTime? supplementEndTime, int semesterId, int lessonId, out string msg)
        {
            msg = "";

            string[] supplementArray = Array.Empty<string>();
            if (!string.IsNullOrWhiteSpace(supplementStudent))
            {
                supplementArray = supplementStudent.Replace('，', ',').Split(',', StringSplitOptions.RemoveEmptyEntries);
            }

            using CBSContext cbs = new();
            using var transaction = cbs.Database.BeginTransaction();
            try
            {
                var lesson = cbs.cbs_lesson.FirstOrDefault(t => t.LessonId == lessonId);
                if (lesson == null) { transaction.Rollback(); return false; }

                int coursePlanId = lesson.CoursePlanId;
                var coursePlan = cbs.cbs_course_plan.FirstOrDefault(t => t.CoursePlanId == coursePlanId);
                if (coursePlan == null) { transaction.Rollback(); return false; }

                var signUpData = (from signup in cbs.cbs_student_signup
                                  join stu in cbs.cbs_student on signup.StudentId equals stu.StudentId
                                  where signup.CoursePlanId == coursePlanId
                                  select stu).ToList();


                List<cbs_student_sign_detail> signInData = signUpData.Where(t => supplementArray.Contains(t.StudentName)).Select(t => new cbs_student_sign_detail { LessonId = lessonId, StudentId = t.StudentId, IsSupplement = true, IsTaster = false }).ToList();

                if (signInData.Count == 0)
                {
                    msg = "未查询到有效数据。";
                    return false;
                }

                cbs.cbs_student_sign_detail.AddRange(signInData);
                cbs.SaveChanges();

                if (supplementStartTime != null && supplementEndTime != null)
                {
                    List<cbs_student_supplement_lesson> supplementData = new List<cbs_student_supplement_lesson>();
                    foreach (var item in signInData)
                    {
                        supplementData.Add(new cbs_student_supplement_lesson { SignInId = item.SighInId, StartTime = supplementStartTime.Value, EndTime = supplementEndTime.Value });
                    }
                    cbs.cbs_student_supplement_lesson.AddRange(supplementData);
                    cbs.SaveChanges();
                }


                SignInOperation(cbs, signInData, coursePlan, lesson, semesterId);

                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return false;
            }

            return true;
        }


        public static bool ImportStudentSignIn(string SignInStudent, string TasterSignInStudent, string IntroduceStudent, int semesterId, int lessonId, out string msg)
        {
            msg = "";

            string[] signInArray = Array.Empty<string>();
            if (!string.IsNullOrWhiteSpace(SignInStudent))
            {
                signInArray = SignInStudent.Replace('，', ',').Split(',', StringSplitOptions.RemoveEmptyEntries);
            }
            string[] tasterSignInArray = Array.Empty<string>();
            //if (!string.IsNullOrWhiteSpace(TasterSignInStudent))
            //{
            //    tasterSignInArray = TasterSignInStudent.Replace('，', ',').Split(',', StringSplitOptions.RemoveEmptyEntries);
            //}
            using CBSContext cbs = new();
            using var transaction = cbs.Database.BeginTransaction();
            try
            {
                var lesson = cbs.cbs_lesson.FirstOrDefault(t => t.LessonId == lessonId);
                int coursePlanId = lesson.CoursePlanId;
                var coursePlan = cbs.cbs_course_plan.FirstOrDefault(t => t.CoursePlanId == coursePlanId);

                var signUpData = (from signup in cbs.cbs_student_signup
                                  join stu in cbs.cbs_student on signup.StudentId equals stu.StudentId
                                  where signup.CoursePlanId == coursePlanId
                                  select stu).ToList();

                List<cbs_student_sign_detail> signInData = signUpData.Where(t => signInArray.Contains(t.StudentName)).Select(t => new cbs_student_sign_detail { LessonId = lessonId, StudentId = t.StudentId, IsSupplement = false, IsTaster = false }).ToList();

                if (signInArray.Length > 0 && signUpData.Count != signInArray.Length)
                {
                    var tmpSignUp = signUpData.Select(t => t.StudentName);
                    string[] signInArrayNoSignUp = signInArray.Except(tmpSignUp).ToArray();

                    var tmpExistStu = (from stu in cbs.cbs_student
                                       where signInArrayNoSignUp.Contains(stu.StudentName)
                                       select stu).ToList();

                    if (tmpExistStu.Count < signInArrayNoSignUp.Length)
                    {
                        msg = "输入的正常签到的学生中包含未注册的学生，请把学生移动到试听中。";
                        transaction.Rollback();
                        return false;
                    }
                    else
                    {
                        msg = "输入的正常签到的学生中包含已注册，但未报名的学生，请先增加学生报到信息。";
                        transaction.Rollback();
                        return false;
                    }
                    //var newSignin = tmpExistStu.Select(t => new cbs_student_sign_detail { LessonId = lessonId, StudentId = t.StudentId, IsSupplement = false, IsTaster = false }).ToList();

                    //signInData = signInData.Concat(newSignin).ToList();
                }


                List<cbs_student_sign_detail> tasterData = new();
                if (!string.IsNullOrWhiteSpace(TasterSignInStudent))
                {
                    //List<string> notExistStu = new();
                    var tmpTasterStu = cbs.cbs_student.FirstOrDefault(t => t.StudentName == TasterSignInStudent);
                    List<cbs_student> students = new List<cbs_student>();
                    if (tmpTasterStu != null)
                    {
                        //if (cbs.cbs_student_sign_detail.Any(t => t.StudentId == tmpTasterStu.StudentId))
                        //{
                        //    msg = "试听学生已经有听课记录，请正常报名签到。";
                        //    transaction.Rollback();
                        //    return false;
                        //}
                        students.Add(tmpTasterStu);

                        if (!cbs.cbs_student_semester_amount.Any(t => t.StudentId == tmpTasterStu.StudentId && t.SemesterId == semesterId))
                        {
                            var data = cbs.cbs_student_amount.FirstOrDefault(t => t.StudentId == tmpTasterStu.StudentId);
                            cbs.cbs_student_semester_amount.Add(new cbs_student_semester_amount
                            {
                                StudentId = tmpTasterStu.StudentId,
                                SemesterId = semesterId,
                                BeforeSemesterBalance = (data == null) ? 0 : data.Balance,
                                Payable = 0,
                                Payment = 0

                            });
                            cbs.SaveChanges();
                        }
                    }
                    else
                    {
                        students.Add(new cbs_student { StudentName = TasterSignInStudent, FirstJoinSemester = coursePlan.SemesterId, FirstJoinClass = coursePlan.ClassId.Value });
                        cbs.cbs_student.AddRange(students);
                        cbs.SaveChanges();


                        List<cbs_student_amount> stuAmounts = new List<cbs_student_amount>();
                        foreach (var item in students)
                        {
                            stuAmounts.Add(new cbs_student_amount { StudentId = item.StudentId, Balance = 0 });
                        }
                        cbs.cbs_student_amount.AddRange(stuAmounts);
                        cbs.SaveChanges();

                        List<cbs_student_semester_amount> stuSemesterAmounts = new List<cbs_student_semester_amount>();
                        foreach (var item in students)
                        {
                            stuSemesterAmounts.Add(new cbs_student_semester_amount { StudentId = item.StudentId, SemesterId = semesterId, BeforeSemesterBalance = 0, Payable = 0, Payment = 0 });
                        }
                        cbs.cbs_student_semester_amount.AddRange(stuSemesterAmounts);
                        cbs.SaveChanges();

                        if (!string.IsNullOrWhiteSpace(IntroduceStudent))
                        {
                            var instroduceStu = cbs.cbs_student.FirstOrDefault(t => t.StudentName == IntroduceStudent);
                            if (instroduceStu == null)
                            {
                                transaction.Rollback();
                                msg = "介绍人未注册，请检查数据。";
                                return false;
                            }

                            cbs_student_bonus bonus = new() { StudentId = students[0].StudentId, IntroduceStudentId = instroduceStu.StudentId, SemesterId = coursePlan.SemesterId };
                            cbs.Add(bonus);
                            cbs.SaveChanges();
                        }


                    }



                    tasterData = students.Select(t => new cbs_student_sign_detail { LessonId = lessonId, StudentId = t.StudentId, IsSupplement = false, IsTaster = true }).ToList();
                    //tasterData.AddRange(tmpTasterStu.Select(t => new cbs_student_sign_detail { LessonId = lessonId, StudentId = t.StudentId, IsSupplement = false, IsTaster = true }).ToList());


                    signInData = signInData.Concat(tasterData).ToList();
                }

                if (signInData.Count == 0)
                {
                    msg = "未查询到有效数据。";
                    return false;
                }

                cbs.cbs_student_sign_detail.AddRange(signInData);
                cbs.SaveChanges();

                SignInOperation(cbs, signInData, coursePlan, lesson, semesterId);

                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return false;
            }

            return true;
        }


        public bool CheckBatchSignInCondition(out string msg)
        {
            msg = "";



            return true;
        }

        public static bool SelectedStudentSignIn(int semesterId, int lessonId, List<int> studentIds, out string msg)
        {
            msg = "";
            using CBSContext cbs = new();
            using var transaction = cbs.Database.BeginTransaction();
            try
            {
                var lesson = cbs.cbs_lesson.FirstOrDefault(t => t.LessonId == lessonId);
                int coursePlanId = lesson.CoursePlanId;
                var coursePlan = cbs.cbs_course_plan.FirstOrDefault(t => t.CoursePlanId == coursePlanId);

                #region 清空Lesson签到信息

                //清空已签到数据
                var signinedData = cbs.cbs_student_sign_detail.Where(t => t.LessonId == lessonId).ToList();
                var stus = signinedData.Select(t => t.StudentId).ToList();

                var stuAmounts = cbs.cbs_student_amount.Where(t => stus.Contains(t.StudentId)).ToList();
                cbs.AttachRange(stuAmounts);
                //学期账户结算
                var stusSemesterAmount = cbs.cbs_student_semester_amount.Where(t => stus.Contains(t.StudentId) && t.SemesterId == coursePlan.SemesterId).ToList();
                cbs.AttachRange(stusSemesterAmount);
                decimal price = coursePlan.CoursePrice * lesson.LessonTimeLong;

                //取消签到消费记录
                var costData = cbs.cbs_student_cost.Where(t => stus.Contains(t.StudentId) && t.CostCoursePlanId == coursePlan.CoursePlanId && t.CostLessonId == lessonId).ToList();

                cbs.cbs_student_cost.RemoveRange(costData);
                cbs.SaveChanges();

                //结算学生账户余额
                for (int i = 0; i < stuAmounts.Count; i++)
                {
                    decimal beforeSemesterBalance = stuAmounts[i].Balance;
                    stuAmounts[i].Balance = stuAmounts[i].Balance + price;
                    cbs.Entry(stuAmounts[i]).Property(x => x.Balance).IsModified = true;

                    var stuSemesterAmount = stusSemesterAmount.FirstOrDefault(t => t.StudentId == stuAmounts[i].StudentId);
                    if (stuSemesterAmount != null)
                    {
                        stuSemesterAmount.Payable -= price;
                    }
                    else
                    {
                        stuSemesterAmount = new cbs_student_semester_amount
                        {
                            StudentId = stuAmounts[i].StudentId,
                            SemesterId = coursePlan.SemesterId,
                            Payable = 0,
                            Payment = 0,
                            BeforeSemesterBalance = beforeSemesterBalance,
                        };
                        cbs.cbs_student_semester_amount.Add(stuSemesterAmount);
                    }
                }
                cbs.SaveChanges();

                //结算教师账户信息
                var teacherSemesterAmount = cbs.cbs_teacher_semester_amount.FirstOrDefault(t => t.TeacherId == lesson.TeacherId && t.SemesterId == coursePlan.SemesterId);
                if (teacherSemesterAmount == null)
                {
                    teacherSemesterAmount = new cbs_teacher_semester_amount
                    {
                        TeacherId = lesson.TeacherId,
                        SemesterId = coursePlan.SemesterId,
                        Receivable = 0,
                        Reeipts = 0
                    };

                    cbs.cbs_teacher_semester_amount.Add(teacherSemesterAmount);
                    cbs.SaveChanges();
                }
                else
                {
                    teacherSemesterAmount.Receivable -= price * stus.Count;
                    cbs.SaveChanges();
                }

                //删除已有签到信息
                if (signinedData.Count > 0)
                {
                    cbs.cbs_student_sign_detail.RemoveRange(signinedData);

                    cbs.SaveChanges();
                }

                #endregion

                var signInData = studentIds.Select(t => new cbs_student_sign_detail { LessonId = lesson.LessonId, StudentId = t, IsSupplement = false, IsTaster = false }).ToList();

                cbs.cbs_student_sign_detail.AddRange(signInData);
                cbs.SaveChanges();

                SignInOperation(cbs, signInData, coursePlan, lesson, semesterId);

                transaction.Commit();
            }
            catch (Exception ex) 
            {
                msg= ex.Message;
                transaction.Rollback();
                return false;
            }

            return true;
        }
    }


}
